<template>
  <div class="upload-container">
    <el-upload
      v-model:file-list="_fileList"
      :auto-upload="false"
      class="upload-demo"
      :limit="props.limit"
      :multiple="true"
      :on-change="handleChange"
      :on-remove="handleRemove"
      op-width="150px"
      :show-file-list="false"
      :size="size"
    >
      <template #trigger>
        <el-button v-if="props.visibleBtn" :icon="Folder" style="margin-bottom: 15px" type="success"> 选择文件 </el-button>
        <slot name="button" style="margin-bottom: 15px"></slot>
      </template>
    </el-upload>
    <el-table :data="tableList" :show-pages="false">
      <el-table-column align="center" label="序号" type="index" width="55" />
      <el-table-column align="center" label="文件类型" prop="filetype" width="100" show-overflow-tooltip />
      <el-table-column align="center" label="文件名称" prop="filename" show-overflow-tooltip />
      <el-table-column align="center" label="文件大小" prop="filesize" width="100" show-overflow-tooltip />
      <el-table-column align="center" label="上传日期" prop="filetime" width="180" show-overflow-tooltip />
      <template v-if="props.configList.length">
        <el-table-column
          v-for="(item, index) of props.configList"
          :key="index"
          align="center"
          :label="item.label"
          :prop="item.prop"
          show-overflow-tooltip
          sortable
        />
      </template>
      <el-table-column align="center" fixed="right" label="操作" width="200">
        <template #default="{ row }">
          <el-button v-if="row?.id" :icon="Download" plain type="primary" @click="download(row)"> 下载 </el-button>
          <el-button v-if="props.visibleBtn" :icon="Delete" plain type="danger" @click="handleRemove(row)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { deleteOne, downloadAttachment, uploadUrl, uploadFile, getList, postRequest } from "@/api/mains";
import { Delete, Download, Folder } from "@element-plus/icons-vue";
import { failMsg, confirm, succMsg } from "@/utils/MessageUtils";
import dayjs from "dayjs";

const props = defineProps({
  modelValue: {
    type: String,
    default: ""
  },
  //单位MB(兆)
  size: {
    type: Number,
    default: 10
  },
  visibleBtn: {
    type: Boolean,
    default: true
  },
  limit: {
    type: Number,
    default: 10
  },
  //是否自动删除
  autoRemove: {
    type: Boolean,
    default: true
  },
  //新增字段
  configList: {
    type: Array,
    default: () => {
      return [];
    }
  },
  url: {
    type: String,
    default: "system/attachment"
  },
  btype: {
    type: String,
    default: ""
  },
  bclass: {
    type: String,
    default: ""
  },
  moduleName: {
    type: String,
    default: "dynamic"
  }
});
const _fileList = ref([]);
const tableList = ref([]);
const delFils = ref([]);
const entityIdRef = ref("");

const emit = defineEmits(["update:modelValue"]);

const handleChange = async (file, fileList) => {
  const size = file.size / 1024 / 1024;
  console.info("handleChange>>>>>>>>>>>>>>>>");
  console.info(file);
  console.info(fileList);
  if (size > props.size) {
    failMsg(`文件大于${props.size}MB`);
    fileList.splice(fileList.length - 1, 1);
  } else {
    let formData = new FormData();
    formData.append("file", file.raw);
    formData.append("moduleName", props.moduleName);

    if (entityIdRef.value == null || entityIdRef.value == "") {
      entityIdRef.value = getBid();
      emit("update:modelValue", JSON.stringify({ type: "files", bid: entityIdRef.value })); //_fileList.value
    }
    formData.append("entityId", entityIdRef.value);
    try {
      const { data } = await uploadFile(formData);
      console.info(data);
      tableList.value.push({
        id: data.id,
        uid: file.uid,
        url: data.uri,
        filetype: file.raw.type,
        filename: file.raw.name,
        filesize: getSize(file.raw.size),
        filetime: ""
      });
      console.info("_fileList>>>>>>>>>>>>>>>>>", _fileList);
      console.info("tableList>>>>>>>>>>>>>>>>>", tableList);
    } catch (error) {
      console.info(error);
      failMsg("上传失败:" + error);
    }
  }
};

const getSize = val => {
  const size = val / 1024 / 1024;
  return `${size < 0.01 ? `${(val / 1024).toFixed(2)}KB` : `${size.toFixed(2)}MB`}`;
};

const handleRemove = file => {
  if (file?.id) {
    confirm("你确定要删除当前附件吗", async () => {
      if (props.autoRemove) {
        const responseData = await deleteOne(props.url, file.id);
        if (responseData.code == 200) {
          succMsg(responseData.msg);
          delRow(file);
        } else {
          failMsg(responseData.msg);
        }
      } else {
        delFils.value.push(file);
      }
    });
  } else {
    delRow(file);
  }
};

const delRow = file => {
  console.info("delRow>>>>>>>>>>>>>>>>>>>>>>>>>", file);
  // let i = 0;
  // tableList.value.forEach((item, index) => {
  //   if (item.id == file.id) {
  //     i = index;
  //   }
  // });
  // _fileList.value.splice(i, 1);
  // tableList.value.splice(i, 1);

  tableList.value = tableList.value.filter(item => item.id !== file.id);

  console.info(tableList);
};

const download = async row => {
  if (row.id) {
    downloadAttachment(row.id)
      .then(res => {
        const link = document.createElement("a");
        const blob = new Blob([res], {
          type: "application/octer-stream"
        });
        link.style.display = "none";
        link.href = URL.createObjectURL(blob);
        link.setAttribute("download", row.filename);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
      .catch(err => {
        console.log(err);
      });
    return true;
  } else {
    failMsg("文件路径不存在");
    return false;
  }
};

/**
 *
 * @param str 判断字符串是否json格式
 */
const checkIsJson = str => {
  if (typeof str == "string") {
    try {
      const obj = JSON.parse(str);
      // 等于这个条件说明就是JSON字符串 会返回true
      if (typeof obj == "object" && obj) {
        return true;
      } else {
        //不是就返回false
        return false;
      }
    } catch (e) {
      return false;
    }
  }
  return false;
};

defineExpose({
  //获取删除的文件列表
  getDelFils: () => {
    return delFils.value;
  },
  //上传
  sendUpload: async id => {
    console.info("sendUpload>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    if (!id) return;
    let isFlag = false;
    const formdata = new FormData();
    if (model_value.value.length) {
      model_value.value.forEach(file => {
        isFlag = file.raw ? true : false;
        formdata.append("files", file.raw ? file.raw : file);
      });
    } else {
      formdata.append("files", "");
    }

    if (isFlag || delFils.value.length) {
      formdata.append("bid", id);
      if (props.btype) {
        formdata.append("btype", props.btype);
      }
      if (props.bclass) {
        formdata.append("bclass", props.bclass);
      }
      if (delFils.value.length) {
        formdata.append(
          "delid",
          delFils.value.map(x => x.id)
        );
      }
      await uploadUrl(props.url, formdata);
      delFils.value = [];
    }
  },
  //初始化加载上传列表
  initUpload: async id => {
    if (!id) return;
    const { data } = await getList(props.url, {
      EQ_bid: id,
      EQ_btype: props?.btype,
      EQ_bclass: props?.bclass
    });
    if (data?.length) {
      data.forEach(item => {
        tableList.value.push({
          filetype: item.filetype,
          filename: item.filename,
          filesize: getSize(item.filesize),
          filetime: item.uptime,
          id: item.id,
          url: item.filepath
        });
      });
      _fileList.value = tableList.value;
    }
  }
});

/**
 * 获取随机生成的业务id
 */
const getBid = () => {
  return dayjs().format("YYYYMMDDHHmmss") + Math.floor(Math.random() * 100000000);
};

watch(
  () => props.modelValue,
  async newVal => {
    console.info("watch>>>>props.modelValue>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", newVal);
    if (newVal && checkIsJson(newVal)) {
      console.info("watch>>>>111>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", newVal);
      tableList.value = [];
      const jsonObj = JSON.parse(newVal);
      entityIdRef.value = jsonObj.bid;
      const { data } = await postRequest(props.url + "/query", { EQ_bid: jsonObj.bid, btype: props.moduleName });
      console.info("query>>>>>>>>>>>data>>>>>>>>>>>>>>>>>", data);
      if (data.rows?.length) {
        const tableItemList = data.rows.map(item => {
          const fileData = {
            filetype: item.filetype,
            filename: item.filename,
            filesize: getSize(item.filesize),
            filetime: item.uptime,
            id: item.id,
            url: item.filepath
          };
          return fileData;
        });
        tableList.value = tableItemList;
      }
    } else {
      console.info("watch>>>>222>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", newVal);
      entityIdRef.value = getBid();
      console.info(entityIdRef.value);
      emit("update:modelValue", JSON.stringify({ type: "files", bid: entityIdRef.value })); //_fileList.value
      tableList.value = [];
    }
    // if (newVal != _fileList.value) {
    //   _fileList.value = newVal;
    // }
  }
);
</script>
<style lang="scss" scoped>
.upload-container {
  :deep() {
    .table-list-empty {
      width: 0;
      height: 0;
      margin: 20px 0;
    }
  }
}
</style>
